package middleware

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"manhe/model"
	"manhe/tool"
	"time"
)

// 自定义一个字符串
var jwtkey = []byte("1233com")

// 用来获取请求的UID
var Uid *UserID

type UserID struct {
	Userid uint
}

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

//创建token中间件

// 颁发token
func Setting(ctx *gin.Context, member model.Userinfo) {
	expireTime := time.Now().Add(1 * 24 * time.Hour)
	fmt.Println(member)
	user_id := member.Id
	//fmt.Println("user_id:", user_id, member)
	claims := &Claims{
		UserId: user_id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), //过期时间
			IssuedAt:  time.Now().Unix(),
			Issuer:    "127.0.0.1",  // 签名颁发者
			Subject:   "user token", //签名主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// fmt.Println(token)
	tokenString, err := token.SignedString(jwtkey)
	if err != nil {
		fmt.Println(err)
	}

	tool.Success(ctx, map[string]interface{}{
		"token":    tokenString,
		"userinfo": member,
	})

}

// 解析token
func Getting(ctx *gin.Context) *UserID {
	tokenString := ctx.GetHeader("token")
	//vcalidate token formate
	if tokenString == "" {
		tool.Failed(ctx, "token已失效")
		ctx.Abort()
		return nil
	}

	token, claims, err := ParseToken(tokenString)
	if err != nil || !token.Valid {
		tool.Failed(ctx, "token已失效")
		ctx.Abort()
		return nil
	}
	fmt.Println(111)
	fmt.Println(claims.UserId)
	uid := new(UserID)
	uid.Userid = claims.UserId
	Uid = uid
	return uid

}

func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	Claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtkey, nil
	})
	return token, Claims, err
}

// 中间件
func JwtToken() gin.HandlerFunc {
	return func(context *gin.Context) {
		//url := context.Request.URL.Path
		//fmt.Println(url)
		//for _, value := range config.Urls {
		//	if value == url {
		//		return
		//	}
		//}
		Getting(context)
	}
}
